<template>
  <div>
    <div v-if="variableObjList.length">
      <div
        class="content-item"
        v-for="(item, idx) in variableObjList"
        :key="idx"
      >
        <span class="item-name">{{ item.title }}</span>

        <div>
          <span class="item-add">
            <el-button type="text" @click="setVariable(idx, item)">
              <el-icon class="item-add-icon" :size="14"
                ><circle-plus
              /></el-icon>
              插入变量</el-button
            >
          </span>
          <div
            class="item-content"
            :id="`public-item-content${idx}`"
            :contenteditable="true"
            @input="rhtChange"
            @change="rhtChange"
            @blur="rhtChange"
            @focus="focus"
            @click="domIndex = item.keyName"
            placeholder="请输入内容"
          ></div>
          <!-- <div
              class="item-content"
              :id="`public-item-content${idx}`"
              :contenteditable="true"
              placeholder="请输入内容"
              v-html="templateDom"
            >
            </div> -->
        </div>
      </div>
    </div>

    <public-form-dialog
      class="public-form-dialog"
      ref="publicFormDialogRef"
      v-model:isDefault="isDefault"
      :isEdit="isEdit"
      @setDefault="setDefault"
      @setDefaultEdit="setDefaultEdit"
    ></public-form-dialog>

  </div>
</template>

<script setup>
import publicFormDialog from "./publicFormDialog.vue";
const variableObjList = ref([]);
const isDefault = ref(false);
const isEdit = ref(false);
const domIndex = ref(null);
const spanInnerHtml = ref("");
const itemDomId = ref("public-item-content1");
const propertyType = ref({
  1: "$_user.",
  2: "$_event.",
  3: '',
});


const props = defineProps({
  domData: {
    type: Object,
    default: {},
  },

  isCareat: {
    type: Boolean,
    default: false,
  },

  comType: {
    type: Boolean,
    default: false,
  },

});
const emits = defineEmits(["subRuleForm"]);

const { domData, isCareat, comType } = toRefs(props);
// const {  } = toRefs(props);
const publicFormDialogRef = ref(null)
const formdata = reactive({ruleFormData:{}})
watch(formdata, (ruleFormData, prevCount) => {
  emits('subRuleForm', formdata.ruleFormData)
},
{deep: true}
)
watch(domData.value, (ruleFormData, prevCount) => {
  variableObjList.value.forEach((el,idx)=> {
    delDomChild(`public-item-content${idx}`)
  })
  setVariableList()
})


const delDomChild = (id)=>{
  let child = document.getElementById(id)
  if(child) {
    child.innerHTML = ''
  }

}

// watchEffect(() => 

// watch(formdata.ruleFormData, (newValue, oldValue) => {
//       
//       
//   });

// const  domList = ref({});

const rhtChange = (e) => {
  const domContent = document.getElementById(e.target.getAttribute("id"));
  
  
  // e.getElementsById("div");
  
  let idList = [];

  let domStr = domContent.innerHTML;
  if (!domContent.firstChild) {
    return;
  }
  // 获取内容中所有节点的id
  if (domContent.children.length) {
    Array.from(domContent.children).forEach((item) => {
      if (item.children.length) {
        Array.from(item.children).forEach((el) => {
          idList.push({
            id: el.getAttribute("id"),
            dataKey: el.getAttribute("data-key"),
            defaultKey: el.getAttribute("default-key"),
            defaultType: el.getAttribute("default-type"),
            length: el.innerHTML.length,
          });
        });
      }
    });
  }

  idList = idList.map((item) => {
    if (item.id !== null) {
      return item;
    }
  });
  
  let parseDomStr = domStr;
  if (idList.length) {
    idList.forEach((el) => {
      
      if (
        parseDomStr.indexOf(`<span id="${el.id}"`) >= 0 &&
        parseDomStr.indexOf("</span> ") >= 0
      ) {
        const subStr = parseDomStr.substring(
          parseDomStr.indexOf(`<span id="${el.id}"`),
          parseDomStr.indexOf("</span> ") + 8
        );
        if(el.defaultType == 3) {
          let dataKey = el.dataKey.replace('https://', '').replace('http://', '') // 去掉链接里的https:// || http://
          parseDomStr = parseDomStr.replace(
            subStr,
            `${dataKey}`
          );
        } else {
          parseDomStr = parseDomStr.replace(
          subStr,
          `{{${propertyType.value[Number(el.defaultType)]}${el.dataKey}${
            el.defaultKey ? ":" + el.defaultKey : ""
          }}}`
        );
        }
        
      }
    });
  }
  parseDomStr = parseDomStr.replace(/<[^>]+>/g, "").replace(/ /g, ""); //去掉字符串里的标签
  

  
  formdata.ruleFormData[domIndex.value].value = parseDomStr;
  formdata.ruleFormData[domIndex.value].idList = idList;

  formdata.ruleFormData[domIndex.value].content = domContent.innerHTML;


};


// 选择变量
const setVariable = (index, item) => {
  domIndex.value = item.keyName;
  itemDomId.value = `public-item-content${index}`;
  isDefault.value = true;
};

// 创建页面节点数据
const setVariableList = () => {
  let tepData = domData.value;
  // domList.value.forEach((item) => {
  //   if (item.template_id == domData.value.template_id) {
  //     tepData = item;
  //   }
  // });
  // 
  let variableTitleList = ''
  if(comType.value == 'publicNumber') {
    variableTitleList = tepData.content.split("\n");
  }


  let regex1 = /\{{(.+?)\}}/g; // {{}} 匹配双花括号包含{{}}
  let regex2 = /(?<=\{{)(.+?)(?=\.DATA}})/g; // {{}} 匹配双花括号不包含{{ .DATA}}
  let variableList = tepData.content.match(regex1) || [];
  

  if(!variableList.length) {
    return
  }

  let variableList2 = tepData.content.match(regex2) || [];
  // formdata.ruleFormData = {}
  // variableList2.forEach(el => {
  //   
  //   tepData.data[el] = {
  //     value: '',
  //     color: "#173177",
  //     content: "",
  //     idList: [],
  //   }
  // });
  // 
  // 
  variableObjList.value = [];
  variableObjList.value = variableList.map((element, idx) => {

    // let ruleFormDataValue = ''
    // if()
    formdata.ruleFormData[variableList2[idx]] = {
      value: (tepData.data !== undefined &&  JSON.stringify(tepData.data)!== '{}' && tepData.data[variableList2[idx]] !== undefined) ? tepData.data[variableList2[idx]].value : '',
      color: "#173177",
      content: "",
      idList: [],
    };
    

    return {
      key: variableObjList[idx],
      title: variableList[idx],
      value: [],
      keyName: variableList2[idx],
    };
  });

  

  
};
// 当前光标的位置信息
const cursor = reactive({
  type: "",
  target: null,
});
const focus = () => {
  recordCursorPos();
};
// 文本框失焦
const blur = () => {
  recordCursorPos();
};
// 记录文本框内的光标位置信息
const recordCursorPos = () => {
  if ((cursor.type = "window")) {
    cursor.target = window.getSelection();
  } else if ((cursor.type = "document")) {
    cursor.target = document.selection.createRange();
  }
};
// 获取当前光标位置信息对象
const getCursorInfo = () => {
  let cursor, type;

  if (window.getSelection) {
    cursor = window.getSelection();
    type = "window";
  } else if (document.selection && document.selection.type !== "Control") {
    // IE < 9
    cursor = document.selection.createRange();
    type = "document";
  }
  return { cursor, type };
};

// 自动聚焦在文本框的最后
const autoFocusTail = () => {
  let el = document.getElementById(itemDomId.value);
  let range = document.createRange();
  let sel = window.getSelection();

  el.focus();
  range.selectNodeContents(el);
  range.collapse(false);
  sel.removeAllRanges();
  sel.addRange(range);
  recordCursorPos();
};

// 以元素节点数据的形式，在光标位置插入内容
const insertEleNode = (eleNode) => {
  let { type, cursor = {} } = getCursorInfo();

  autoFocusTail();
  cursor = getCursorInfo().cursor;
  let range;
  if (type === "window") {
    if (cursor.getRangeAt && cursor.rangeCount) {
      let el = document.createElement("div"),
        frag = document.createDocumentFragment(),
        node,
        lastNode;
      let span = window.document.createElement("span");
      span.innerHTML = eleNode;
      
      span.addEventListener("click", function ($event) {
        
        setItemDom($event);
      });
      el.appendChild(span);
      range = cursor.getRangeAt(0);
      range.deleteContents();

      while ((node = el.firstChild)) {
        lastNode = frag.appendChild(node);
      }

      range.insertNode(frag);

      if (lastNode) {
        range = range.cloneRange();
        range.setStartAfter(lastNode);
        range.collapse(true);
      }
    }
  } else if ((type = "document")) {
    cursor.pasteHTML(eleNode);
  }
  autoFocusTail();
};

// 编辑添加的子节点
const setItemDom = (event) => {
  
  // event.currentTarget.attributes
  
  // 防止点到节点后面的空格
  if (!event.target.id) {
    return;
  }
  publicFormDialogRef.value.theEchoForm(
    {
      value: event.srcElement.getAttribute("data-key"),
      input: event.srcElement.getAttribute("default-key"),
    }
  )
  isDefault.value = true;
  // 
  isEdit.value = true;
  // spanInnerHtml.value = event.target
  // spanInnerHtml.value.innerHTML = '11111'
  
  // 
  spanInnerHtml.value = document.getElementById(event.target.id);
  

  console.log(
    '[ document.getElementById("id名字"); ] >',
    spanInnerHtml.value.getAttribute("data-key")
  );
};

// 编辑属性返回的
const setDefaultEdit = (val, isDefaultValue) => {
  isEdit.value = false;
  spanInnerHtml.value.innerHTML = val.label;
  spanInnerHtml.value.setAttribute("data-key", val.value);
  spanInnerHtml.value.setAttribute("default-key", isDefaultValue);
  spanInnerHtml.value.setAttribute("default-type", val.pathValues[0]);
};
// 生成随机数用来创建Dom的ID
const randomString = (length) => {
  const str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  let result = "";
  for (let i = length; i > 0; --i)
    result += str[Math.floor(Math.random() * str.length)];
  return result;
};
const variableStyle = ref('color:#001E70;background:#F5F7FA;line-height:25px;border-radius:4px;display:inline-block')
// 添加属性返回的
const setDefault = (val, isDefaultValue) => {
  // 
  // 

  const tesDom = ` <span id="${randomString(30)}" style="${variableStyle.value}" data-key="${
    val.value
  }" default-key="${isDefaultValue}" class="setDomClass" default-type="${
    val.pathValues[0]
  }" class="variable" contenteditable='${false}'>【${val.label}】</span> `;

  // 
  //   // const tesDom = "<div>ssss</div>"
  insertEleNode(tesDom);
};

// 回显数据
const setDomInnerHtml = (val) => {
  // 
  // 

  // ;
  let dom = "";
  nextTick(() => {
    variableObjList.value.forEach((item, index) => {
      // 
      dom = document.getElementById(`public-item-content${index}`);
      // 
      dom.innerHTML = val.data[item.keyName].content || val.data[item.keyName].value;
      val.data[item.keyName].idList.forEach((el) => {
        // 
        // 
        // document.querySelectorAll("setDomClass").click(function () {
        //   
        // });
        document.getElementById(el.id).onclick =function($event) {
          setItemDom($event);
        }
      });
    });
    // formdata.ruleFormData = domData.value
  });
};


// 获取模板列表
// const getPublicNumber = async () => {
//   // 
//   let rs = await CanvasApi.getPublicNumber();
//   if (rs.code == 200) {
    
//     domList.value  = rs.payload.template_list
    
//   }
// };



onMounted( async() => {
  // await getPublicNumber(); // 获取模板列表
  
  setVariableList() // 创建结构

  if(!isCareat.value) {
    // 
    // 
    // 
    setDomInnerHtml(domData.value); // 插入数据
  }

  // ;
});
</script>
<style lang="scss" scoped>
.content {
  width: 480px;
  background: #fafcff;
  border-radius: 4px;
  padding: 19px 16px;
}
.content-title {
  height: 22px;
  display: flex;
  align-items: center;
  .header-icon {
    display: inline-block;
    width: 4px;
    height: 16px;
    margin-right: 8px;
    background: var(--el-color-primary);
    border-radius: 1px;
  }
  .header-title {
    height: 22px;
    font-size: 14px;
    font-weight: 500;
    color: #606266;
    line-height: 22px;
  }
}
.content-item {
    width: 500px;
  .item-name {
    height: 22px;
    font-size: 14px;
    font-weight: 400;
    color: #606266;
    line-height: 22px;
  }
  .item-add {
    display: inline-block;
    width: 100%;
    height: 36px;
    position: relative;
    z-index: 10;
    top: 5px;
    border: 1px solid #E4E7ED;
    background: #fff;
    border-top-left-radius: 6px;
    border-top-right-radius: 6px;
    .item-add-icon {
      margin: 0px 4px 0px 16px;
    }
  }
  div[contenteditable="true"]:empty:before {
    content: attr(placeholder);
    color: #a9a9a9;
  }
  .item-content {
    word-break: break-all;
    width: calc(100% - 20px);
    height: 70px;
    overflow: hidden;
    white-space: pre-wrap;
    border: 1px solid #E4E7ED;
    padding: 10px;
    background: #fff;
    border-bottom-left-radius: 6px;
    border-bottom-right-radius: 6px;
    user-select: none;
  }

  .item-content:focus-visible {
    outline: none !important;
  }
  // :deep(.el-textarea__inner, .el-textarea__inner:hover) {
  //   box-shadow: none;
  //   border: 1px solid #606266;
  //   border-top: none;
  //   border-radius: 0;
  //   border-bottom-left-radius: 6px;
  //   border-bottom-right-radius: 6px;
  //   padding-top: 10px;
  // }
}

.variable {
  color: red;
  font-size: 30px;
}

</style>
